/**    
 * @{#} ChatActivity_V1_1.java Create on 2014-10-13 下午3:06:18    
 *          
 * @author <a href="mailto:evan0502@qq.com">Evan</a>   
 * @version 1.0    
 */
package com.smiier.skin;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.o.app.event.listener.OBitmapLoadCallBack;
import cn.o.app.json.JsonDate;
import cn.o.app.json.JsonUtil;
import cn.o.app.media.PickPhotoTask;
import cn.o.app.media.PickPhotoTask.PickPhotoListener;
import cn.o.app.media.TakePhotoTask;
import cn.o.app.media.TakePhotoTask.TakePhotoListener;
import cn.o.app.net.INetTask;
import cn.o.app.net.NetTaskListener;
import cn.o.app.ui.OActionSheet;
import cn.o.app.ui.OActionSheet.OActionItem;
import cn.o.app.ui.OActionSheet.OnActionItemClickListener;
import cn.o.app.ui.OImageView;
import cn.o.app.ui.photo.PhotoActivity;
import cn.o.app.ui.photo.PhotoExtra;
import cn.o.app.util.OUtil;
import cn.skinapp.R;

import com.evan.common.adapter.BaseListAdapter;
import com.evan.common.connection.ConnectionCommon;
import com.evan.common.connection.remotefile.RemoteImageDownloader;
import com.evan.common.handler.ImageHandler;
import com.evan.common.handler.RequestHandler;
import com.evan.common.handler.callback.HandlerCallback;
import com.evan.common.handler.callback.ImageHandlerCallback;
import com.evan.common.pullrefresh.PullToRefreshBase;
import com.evan.common.pullrefresh.PullToRefreshBase.OnRefreshListener;
import com.evan.common.pullrefresh.PullToRefreshListView;
import com.evan.common.utils.CacheCommon;
import com.evan.common.utils.DeviceUtility;
import com.evan.common.utils.RecordingUtil;
import com.lidroid.xutils.BitmapUtils;
import com.smiier.skin.constant.Constant;
import com.smiier.skin.extra.QuestionAnswerExtra;
import com.smiier.skin.intercept.RequestTaskIntercept;
import com.smiier.skin.net.QuestionGetTask;
import com.smiier.skin.net.RelationshipGetTask;
import com.smiier.skin.net.QuestionGetTask.QuestionGetRequest;
import com.smiier.skin.net.QuestionGetTask.QuestionGetResponse;
import com.smiier.skin.net.RelationshipGetTask.RelationshipGetRequest;
import com.smiier.skin.net.RelationshipGetTask.RelationshipGetResponse;
import com.smiier.skin.net.RelationshipSetTask;
import com.smiier.skin.net.RelationshipSetTask.RelationshipSetRequest;
import com.smiier.skin.net.RelationshipSetTask.RelationshipSetResponse;
import com.smiier.skin.net.entity.QuestionAnswer;
import com.smiier.skin.net.entity.Session;
import com.smiier.skin.net.entity.User;
import com.smiier.skin.net.entity.UserWrapper;
import com.smiier.skin.receiver.MessageReceiver;
import com.smiier.skin.ui.BasicActivity;
import com.smiier.skin.ui.TextAddQuotes;
import com.smiier.skin.util.GlobalSettings;
import com.smiier.skin.util.KeyValueUtil;
import com.smiier.skin.utils.CommonUtility;
import com.smiier.skin.utils.RemoteVoiceDownloader;
import com.smiier.skin.vo.ChatVo;
import com.umeng.analytics.MobclickAgent;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressLint({ "HandlerLeak", "InflateParams", "ClickableViewAccessibility" })
public class ChatActivity extends BasicActivity implements
		OnRefreshListener<ListView> {

	private PullToRefreshListView list_session;

	EditText edit_sendmessage;

	Button btn_more;

	Button btn_send;

	Button btn_keyboard;

	Button btn_voice;

	TextView btn_press_to_voice;

	private RelativeLayout rl_input;
	private HorizontalScrollView mHsvImg;
	
	private static boolean isClick;

	private JSONObject all, question, patient, doctor;
	ArrayList<Object> recordArray = new ArrayList<Object>();
	HashMap<String, Object> params = new HashMap<String, Object>(),
			params_record = new HashMap<String, Object>(),
			readParams = new HashMap<String, Object>();
	ChatAdapter adapter;
	String startid = "";
	int qid, uid;
	TextAddQuotes text_question_name;
	public static int currentQid;
	public boolean mTreatment;
	User mUser;
	TextView mSuiFang;
	UserWrapper mUserWrapper;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_chat);
		list_session = (PullToRefreshListView) findViewById(R.id.list_session);
		edit_sendmessage = (EditText) findViewById(R.id.edit_sendmessage);
		btn_more = (Button) findViewById(R.id.btn_more);
		btn_send = (Button) findViewById(R.id.btn_send);
		btn_keyboard = (Button) findViewById(R.id.btn_keyboard);
		btn_press_to_voice = (TextView) findViewById(R.id.btn_press_to_voice);
		btn_voice = (Button) findViewById(R.id.btn_voice);
		rl_input = (RelativeLayout) findViewById(R.id.rl_input);
		mTreatment = getIntent().getBooleanExtra(Constant.KEY_TREATMENT, false);
		mSuiFang = (TextView) findViewById(R.id.qi_dong_sui_fang);
		
		init();
		setNavRightBtn("操作");
		/*View headView = LayoutInflater.from(activity).inflate(
				R.layout.item_chat_head, null);*/
		
		
		LinearLayout headView = findViewById(R.id.item_chat_head,LinearLayout.class);
		
		try {
			all = new JSONObject(getIntent().getStringExtra(
					Constant.IDENTITY_KEY));
			if (!mTreatment) {
				// 初始化头部view和数据

				text_question_name = (TextAddQuotes) headView
						.findViewById(R.id.text_question_name);
				TextView textUserInfo = (TextView) headView
						.findViewById(R.id.text_user_info);
				mHsvImg = (HorizontalScrollView) headView
						.findViewById(R.id.hsv_imgs);
				LinearLayout llImg = (LinearLayout) headView
						.findViewById(R.id.ll_imgs);
				// 初始化隐藏，需要通过点击头部来控制隐藏和展示
				mHsvImg.setVisibility(View.GONE);

				boolean isDoctor = CommonUtility.isDoctor();

				question = all.getJSONObject("Question");
				patient = all.getJSONObject("Patient_User");
				doctor = all.getJSONObject("Doctor_User");

				qid = question.getInt("Qid");

				uid = patient.getInt("Uid");

				notifiSessionViewNoRead();

				if (question.getInt("Status") == 3) {
					finishTip();
				}

				// .setText(question.getString("Content"));

				// 用户信息
				StringBuilder sb = new StringBuilder();
				String sex = question.getInt("Sex") == 0 ? "男" : "女";
				sb.append(sex).append("，").append(question.getInt("Age"))
						.append("岁");

				String nation = patient.getString("Nation");
				if (!CommonUtility.isNull(nation)) {
					// sb.append("，").append(nation);
				}
				String maritalStatus = patient.getInt("Marital_Status") == 0 ? "未婚"
						: "已婚";
				// sb.append("，").append(maritalStatus);

				StringBuilder otherInfoBuilder = new StringBuilder();
				String bingshi = CommonUtility.convertJSONArray2String(
						question.getJSONArray("MedicalHistory"), "、");
				String guoMinShi = CommonUtility.convertJSONArray2String(
						question.getJSONArray("DrugAllergen"), "、");
				String puTongYaoWuGuoMin = CommonUtility
						.convertJSONArray2String(
								question.getJSONArray("Allergen"), "、");
				String jiaren = CommonUtility.convertJSONArray2String(
						question.getJSONArray("FamilyMedicalHistory"), "、");

				if (!CommonUtility.isNull(bingshi)) {
					otherInfoBuilder.append(bingshi).append("、");
				}
				if (!CommonUtility.isNull(guoMinShi)) {
					otherInfoBuilder.append(guoMinShi).append("、");
				}
				if (!CommonUtility.isNull(puTongYaoWuGuoMin)) {
					otherInfoBuilder.append(puTongYaoWuGuoMin).append("、");
				}
				if (!CommonUtility.isNull(jiaren)) {
					otherInfoBuilder.append(jiaren);
				}
				if (!CommonUtility.isNull(otherInfoBuilder)) {
					sb.append("，").append("对").append(otherInfoBuilder);
				}
				String c = sb.toString();
				if (c.endsWith("、")) {
					c = c.substring(0, c.length() - 1);
				}
				textUserInfo.setText(c);
				// 图片显示
				JSONArray pics = question.getJSONArray("Pic");
				llImg.removeAllViews();
				if (pics.length() > 0) {
					String[] picStrs = new String[pics.length()];
					for (int i = 0; i < pics.length(); i++) {
						OImageView layout = new OImageView(activity);
						layout.setIsRoundRect(true);
						layout.setId(R.id.imgLayout_show);
						layout.setScaleType(ScaleType.CENTER_CROP);
						LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
								(int) OUtil.dp2px(activity, 70),
								(int) OUtil.dp2px(activity, 70));
						layoutParams.setMargins(0, 0,
								(int) OUtil.dp2px(activity, 8), 0);
						layout.setLayoutParams(layoutParams);

						final String path = pics.getString(i) + Constant.IMG_TH;
						mBitmapUtils.display(layout,
								GlobalSettings.SERVER_IMG_URL + path);
						llImg.addView(layout);
						// layout.setImageFileTag(pics.getString(i)
						// + Constant.IMG_SRC);
						layout.setOnClickListener(listener);
						layout.setTag(i);
						layout.setTag(R.id.tag_obj, picStrs);
						picStrs[i] = ConnectionCommon.getInstance().REQUEST_PIC_PATH
								+ pics.getString(i) + Constant.IMG_SRC;
					}
				}

				TextView questionTip = (TextView) headView
						.findViewById(R.id.text_question_tip);
				int status = question.getInt("Status");
				if (isDoctor) {
					setNavTitle(patient.getString("Name"));
					if (status != 3) {
						setNavRightBtn("操作");
					}
					// 显示友好提示
					TextView textDoctorTip = (TextView) headView
							.findViewById(R.id.text_doctor_tip);
					String content = "<font color='#777777'>您可以通过图文对话与患者了解病情，问诊完成后请点击右上角</font> <font color='#49d29d'>创建解答</font> <font color='#777777'>按钮，为患者创建一份正式解答意见，创建解答意见后这个问题会被关闭</font>";
				//	textDoctorTip.setText(Html.fromHtml(content));
					//textDoctorTip.setVisibility(View.VISIBLE);
				} else {
					setNavTitle(doctor.getString("Name"));
				}
				if (status == 3) {
					questionTip.setText("解答完成");
					// questionTip.setCompoundDrawablesWithIntrinsicBounds(
					// getResources().getDrawable(
					// R.drawable.chat_status_finish), null, null,
					// null);
					// questionTip.setTextColor(getResources().getColor(R.color.red));
				}

			} else {
				mUser = JsonUtil.convert(all.toString(), User.class);
				setNavTitle(mUser.Name);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		list_session.setPullLoadEnabled(false);
		list_session.setOnRefreshListener(this);
		if (!mTreatment) {
//			list_session.getListView().addHeaderView(headView);
			headView.setVisibility(View.VISIBLE);
		}
		adapter = new ChatAdapter(activity, recordArray, all);
		list_session.setAdapter(adapter);
		
		list_session.setSelected(ListView.FOCUS_DOWN);

		list_session.getRefreshableView().setOnTouchListener(
				new OnTouchListener() {

					@Override
					public boolean onTouch(View view, MotionEvent event) {
						CommonUtility.hideKeyboard(activity, view);
						return false;
					}
				});

		// 获取最后一次缓存的聊天记录用于展示
		ArrayList<CacheCommon> caches = dbUtil.queryCache(getClass()
				.getSimpleName(), uid);
		
		Log.i("testchatdata", "caches:" + caches.size());
		
		
		if (caches.size() > 0) {
			String data = caches.get(0).data;
			try {
				JSONArray array = new JSONArray(data);
				CommonUtility.putAll(recordArray, array, true);
				adapter.notifyUpdate();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		try {
			params.put(Constant.PARAM_API, "Answer.Session.Get");
			// params.put(Constant.PARAM_API, "Dialog.Send");
			params.put(Constant.PARAM_QID, qid);
			params.put("pagesize", Constant.pageSize);
			params.put(Constant.PARAM_TOKEN, GlobalSettings.sToken);
			params.put("IS_new", 1);
			params.put("appname", Constant.APP_NAME);
			// list_session.doPullRefreshing(true);
			//loadData();

			params_record.put(Constant.PARAM_QID, qid);
			params_record.put(Constant.PARAM_TOKEN, GlobalSettings.sToken);
			// params_record.put(Constant.PARAM_API, "Answer.Session.Send");
			params_record.put(Constant.PARAM_API, "Dialog.Send");

			params_record.put("Uid", patient.getString("Uid"));
			params_record.put("appname", Constant.APP_NAME);
			// readParams.put(Constant.PARAM_API, "Answer.Session.Received");
			readParams.put(Constant.PARAM_API, "Answer.Session.Received");
			readParams.put("qid", qid);
			readParams.put("appname", Constant.APP_NAME);
			readParams.put(Constant.PARAM_TOKEN, GlobalSettings.sToken);
		} catch (Exception e) {
			e.printStackTrace();
		}
		edit_sendmessage.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
			}

			@Override
			public void afterTextChanged(Editable arg0) {
				if (!CommonUtility.isNull(arg0)) {
					btn_send.setVisibility(View.VISIBLE);
					btn_more.setVisibility(View.GONE);
				} else {
					btn_send.setVisibility(View.GONE);
					btn_more.setVisibility(View.VISIBLE);
				}
			}
		});

		btn_press_to_voice.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				return false;
			}
		});

		IntentFilter filter = new IntentFilter(Constant.RECEIVER_CHATING);
		registerReceiver(receiver, filter);

		// 初始化草稿
		ArrayList<CacheCommon> datas = dbUtil.queryCache(getClass()
				.getSimpleName(), uid + "_drafts");

		if (datas.size() > 0) {
			edit_sendmessage.setText(datas.get(0).data);
		}

		// 清除关联的通知
		NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		notificationManager.cancel(MessageReceiver.notifyId);
		getUserWrapper();
		mSuiFang.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				mSuiFang.setVisibility(View.GONE);
				RelationshipSetTask task = new RelationshipSetTask();
				RelationshipSetRequest req = new RelationshipSetRequest();
				req.appname = Constant.APP_NAME;
				req.IS_RSAcceptMSG = 1;
				try {
					req.rsuid = patient.getLong("Uid");
					req.token = GlobalSettings.sToken;
					task.setRequest(req);
					add(task);
					task.addListener(new NetTaskListener<RelationshipSetTask.RelationshipSetRequest, RelationshipSetTask.RelationshipSetResponse>() {

						@Override
						public void onComplete(
								INetTask<RelationshipSetRequest, RelationshipSetResponse> task,
								RelationshipSetResponse response) {
							if(response!=null&&response.ResultCode==200){
								mUserWrapper .RelationShip= response.Res;
								mSuiFang.setVisibility(View.GONE);
								btn_press_to_voice.setVisibility(View.GONE);
								
								btn_voice.setFocusable(true);
								btn_voice.setEnabled(true);
								btn_keyboard.setFocusable(true);
								btn_keyboard.setEnabled(true);
								btn_more.setFocusable(true);
								btn_more.setEnabled(true);
							}
						}

						@Override
						public void onException(
								INetTask<RelationshipSetRequest, RelationshipSetResponse> task,
								Exception e) {
							
						}
					});
					
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		});
	}

	private void getUserWrapper() {
		RelationshipGetTask task = new RelationshipGetTask();
		RelationshipGetRequest req = new RelationshipGetRequest();
		req.appname = Constant.APP_NAME;
		req.token = GlobalSettings.sToken;
		req.rsuids = new ArrayList<Long>();
		try {
			req.rsuids.add(patient.getLong("Uid"));
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		task.setRequest(req);
		task.addListener(new NetTaskListener<RelationshipGetTask.RelationshipGetRequest, RelationshipGetTask.RelationshipGetResponse>() {

			@Override
			public void onComplete(
					INetTask<RelationshipGetRequest, RelationshipGetResponse> task,
					RelationshipGetResponse response) {
				if (response != null && response.ResultCode == 200
						&& response.Res.Users.size() > 0) {
					mUserWrapper = response.Res.Users.get(0);
					if(mUserWrapper.RelationShip.IS_RSAcceptMSG==1){
						//会话中
						
						mSuiFang.setVisibility(View.GONE);		
						
					}else{
					//关闭会话
						mSuiFang.setVisibility(View.VISIBLE);
						btn_press_to_voice.setVisibility(View.GONE);
						
						btn_voice.setFocusable(false);
						btn_voice.setEnabled(false);
						btn_keyboard.setFocusable(false);
						btn_keyboard.setEnabled(false);
						btn_more.setFocusable(false);
						btn_more.setEnabled(false);
					}
				}
			}

			@Override
			public void onException(
					INetTask<RelationshipGetRequest, RelationshipGetResponse> task,
					Exception e) {

			}
		});
		add(task);
	}

	private void initQuestion() {
		QuestionGetTask task = new QuestionGetTask();
		QuestionGetRequest req = new QuestionGetRequest();
		req.appname = Constant.APP_NAME;
		req.token = GlobalSettings.sToken;
		req.qids = new ArrayList<Long>();
		req.qids.add(Long.parseLong(currentQid + ""));
		task.setRequest(req);
		add(task);
		task.addListener(new NetTaskListener<QuestionGetTask.QuestionGetRequest, QuestionGetTask.QuestionGetResponse>() {

			@Override
			public void onException(
					INetTask<QuestionGetRequest, QuestionGetResponse> task,
					Exception e) {

			}

			@Override
			public void onComplete(
					INetTask<QuestionGetRequest, QuestionGetResponse> task,
					QuestionGetResponse response) {
				if (response != null && response.Res.size() > 0) {
					QuestionAnswer answer = response.Res.get(0);
					try {
						all = JsonUtil.convertToObject(answer);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

			}
		});
	}

	private void notifiSessionViewNoRead() {
		Intent intent = new Intent(Constant.RECIVER_SESSION_ITEM_NOREAD_COUNT);

		intent.putExtra("qid", qid + "");
		sendBroadcast(intent);

		Intent refreshIntent = new Intent(Constant.RECIVER_SESSION_TAB_NOREAD);
		getContext().sendBroadcast(refreshIntent);
	}

	private Dialog dialog;
	private ImageView img_recording_anim;
	private LinearLayout ll_recording;
	private RelativeLayout ll_cancel_tip, ll_time_too_short;

	// 录音时显示Dialog
	void showVoiceDialog() {
		if (CommonUtility.isNull(dialog)) {
			dialog = new Dialog(activity, R.style.recordDialogStyle);
			dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dialog.getWindow().setFlags(
					WindowManager.LayoutParams.FLAG_FULLSCREEN,
					WindowManager.LayoutParams.FLAG_FULLSCREEN);
			dialog.setContentView(R.layout.recording_dialog);
			img_recording_anim = (ImageView) dialog
					.findViewById(R.id.img_recording_anim);
			ll_cancel_tip = (RelativeLayout) dialog
					.findViewById(R.id.ll_cancel_tip);
			ll_recording = (LinearLayout) dialog
					.findViewById(R.id.ll_recording);
			ll_time_too_short = (RelativeLayout) dialog
					.findViewById(R.id.ll_time_too_short);
		}
		dialog.show();
	}

	RecordingUtil recordUtil;
	private int voiceValue;

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (!btn_press_to_voice.isShown()) {
			return super.onTouchEvent(event);
		}
		if (!CommonUtility.isExistSDCard()) {
			Toast.makeText(this, "sdcard没有挂载", Toast.LENGTH_LONG).show();
			return false;
		}

		int[] location = new int[2];
		btn_press_to_voice.getLocationInWindow(location); // 获取在当前窗口内的绝对坐标
		int btn_rc_Y = location[1];
		int btn_rc_X = location[0];
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			if (event.getY() > btn_rc_Y && event.getX() > btn_rc_X) {// 判断手势按下的位置是否是语音录制按钮的范围内
				
				if(!isClick){
					isClick = true;
					btn_press_to_voice
					.setBackgroundResource(R.drawable.bg_input_pressed);
			showVoiceDialog();
			ll_cancel_tip.setVisibility(View.GONE);
			ll_recording.setVisibility(View.VISIBLE);
			// 初始化录音工具
			recordUtil = new RecordingUtil(activity);
			recordUtil.startRecord();
			new Thread(ImgThread).start();
				}
				
				
			}
		} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
			if (event.getY() > btn_rc_Y && event.getX() > btn_rc_X) {// 判断手势按下的位置是否是语音录制按钮的范围内
				if (!CommonUtility.isNull(dialog)) {
					btn_press_to_voice
							.setBackgroundResource(R.drawable.bg_input_pressed);
					ll_cancel_tip.setVisibility(View.GONE);
					ll_recording.setVisibility(View.VISIBLE);
				}
			} else {
				if (!CommonUtility.isNull(dialog)) {
					ll_cancel_tip.setVisibility(View.VISIBLE);
					ll_recording.setVisibility(View.GONE);
				}
			}
		} else if (event.getAction() == MotionEvent.ACTION_UP) {// 松开手势时执行录制完成
			
			isClick = false;
			if (!CommonUtility.isNull(recordUtil)) {
				btn_press_to_voice.setBackgroundResource(R.drawable.bg_input);
				recordUtil.stopRecord();
				int voiceTime = recordUtil.getVoiceTime();
				if (voiceTime < 1) {
					if (!CommonUtility.isNull(dialog)) {
						ll_time_too_short.setVisibility(View.VISIBLE);
						ll_cancel_tip.setVisibility(View.GONE);
						ll_recording.setVisibility(View.GONE);
						imgHandle.sendEmptyMessage(2);
					}
				} else {
					if (!CommonUtility.isNull(dialog)) {
						if (ll_recording.isShown()) {
							// 发送语音
							String content = recordUtil.getVoicePath();

							if (!CommonUtility.isNull(content)) {
								ChatVo vo = new ChatVo();
								vo.content = content;
								vo.isLocal = true;
								vo.voiceLength = voiceTime;
								vo.contentType = Constant.TYPE_CHAT_VOICE;
								send(vo);
								recordUtil = null;
							} else {
								CommonUtility.toast(activity, "发送内容不能为空");
							}
						}
						dialog.dismiss();
						dialog = null;
					}
				}
			}
		}
		return super.onTouchEvent(event);
	}

	// 录音线程
	private Runnable ImgThread = new Runnable() {

		@Override
		public void run() {
			while (!CommonUtility.isNull(recordUtil)
					&& recordUtil.isRecording()) {
				try {
					Thread.sleep(200);
					voiceValue = recordUtil.getVolume();
					imgHandle.sendEmptyMessage(1);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	};

	Handler imgHandle = new Handler() {
		@Override
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case 2:
				try {
					Thread.sleep(1000);
					ll_time_too_short.setVisibility(View.GONE);
					recordUtil.deleteRecordFile();
					recordUtil = null;
				} catch (Exception e) {
					e.printStackTrace();
				}
				dialog.dismiss();
				break;
			case 1:
				setDialogImage();
				break;
			}

		}
	};

	// 录音Dialog图片随声音大小切换
	void setDialogImage() {
		if (voiceValue < 200.0) {
			img_recording_anim.setImageResource(R.drawable.record_volume_1);
		} else if (voiceValue > 200.0 && voiceValue < 400) {
			img_recording_anim.setImageResource(R.drawable.record_volume_2);
		} else if (voiceValue > 400.0 && voiceValue < 800) {
			img_recording_anim.setImageResource(R.drawable.record_volume_3);
		} else if (voiceValue > 800.0 && voiceValue < 1600) {
			img_recording_anim.setImageResource(R.drawable.record_volume_4);
		} else if (voiceValue > 1600.0 && voiceValue < 3200) {
			img_recording_anim.setImageResource(R.drawable.record_volume_5);
		} else if (voiceValue > 3200.0 && voiceValue < 5000) {
			img_recording_anim.setImageResource(R.drawable.record_volume_6);
		} else if (voiceValue > 5000.0 && voiceValue < 7000) {
			img_recording_anim.setImageResource(R.drawable.record_volume_7);
		} else if (voiceValue > 7000.0 && voiceValue < 10000.0) {
			img_recording_anim.setImageResource(R.drawable.record_volume_8);
		} else if (voiceValue > 10000.0 && voiceValue < 14000.0) {
			img_recording_anim.setImageResource(R.drawable.record_volume_9);
		} else if (voiceValue > 14000.0 && voiceValue < 17000.0) {
			img_recording_anim.setImageResource(R.drawable.record_volume_10);
		} else if (voiceValue > 17000.0 && voiceValue < 20000.0) {
			img_recording_anim.setImageResource(R.drawable.record_volume_11);
		} else if (voiceValue > 20000.0) {
			img_recording_anim.setImageResource(R.drawable.record_volume_11);
		}
	}

	// JSONArray cacheArray = new JSONArray();

	void loadData() {
		params.put("startid", startid);
		RequestTaskIntercept.requestIntercept(activity, Constant.URL.REQUEST,
				new RequestHandler(activity, new HandlerCallback() {

					@Override
					public void callback(Object o) {
						if (!CommonUtility.isNull(o)) {
							list_session.doComplete();
							JSONObject object = (JSONObject) o;
							if (CommonUtility.response200(object)) {
								try {
									JSONArray array = object.getJSONObject(
											Constant.JSON_PARAM_RES)
											.getJSONArray("Session");
									if (array.length() > 0) {
										if (CommonUtility.isNull(startid)) {
										//	recordArray.clear();
									//	 cacheArray = array;

											dbUtil.saveOrUpdate(
													ChatActivity.class
															.getSimpleName(),
													array.toString(), uid);
										}
										CommonUtility.putAll(recordArray,
												array, true);
										adapter.notifyUpdate(recordArray);
										if (array.length() > 0) {
											StringBuilder ids = new StringBuilder();
											int length = array.length();
											for (int i = 0; i < length; i++) {
												try {
													ids.append(array
															.getJSONObject(i)
															.getString("id"));
													if (i < length - 1) {
														ids.append(",");
													}
												} catch (Exception e) {
													e.printStackTrace();
												}
											}
											setReaded(ids.toString());
										}

										if (CommonUtility.isNull(startid)) {
											list_session
													.getListView()
													.smoothScrollToPosition(
															list_session
																	.getListView()
																	.getBottom());
										} else {
											if (DeviceUtility.DeviceInfo
													.getSystemSDKVersion() >= 11) {
												list_session
														.getListView()
														.smoothScrollToPositionFromTop(
																array.length(),
																0, 0);
											} else {
												list_session.getListView()
														.setSelection(
																array.length());
											}
										}
										startid = array.getJSONObject(
												array.length() - 1).getString(
												"id");
									}
								} catch (Exception e) {
									e.printStackTrace();
								}
							}
						}
					}
				}), false, params);
	}

	int isComment = 0;

	public void onClick(View view) {
		super.onClick(view);
		int id = view.getId();
		if (id == R.id.btn_more) {
			onClickMore();
		} else if (id == R.id.btn_send) {
			String content = edit_sendmessage.getText().toString();
			if (!CommonUtility.isNull(content)) {
				ChatVo vo = new ChatVo();
				vo.content = content;
				vo.contentType = Constant.TYPE_CHAT_TEXT;
				send(vo);
				edit_sendmessage.setText(null);
			} else {
				CommonUtility.toast(activity, "发送内容不能为空");
			}
		} else if (id == R.id.btn_voice) {
			edit_sendmessage.setVisibility(View.GONE);
			btn_voice.setVisibility(View.GONE);
			btn_keyboard.setVisibility(View.VISIBLE);
			btn_press_to_voice.setVisibility(View.VISIBLE);
			CommonUtility.hideKeyboard(activity, view);
		} else if (id == R.id.btn_keyboard) {
			edit_sendmessage.setVisibility(View.VISIBLE);
			btn_voice.setVisibility(View.VISIBLE);
			btn_keyboard.setVisibility(View.GONE);
			btn_press_to_voice.setVisibility(View.GONE);
		} else if (id == R.id.rl_question_detail) {
			/*
			 * if (mHsvImg.getVisibility() == View.VISIBLE) {
			 * mHsvImg.setVisibility(View.GONE); } else {
			 * mHsvImg.setVisibility(View.VISIBLE); }
			 */
			Intent intent = new Intent(activity, QuestionDetailActivity.class);
			intent.putExtra(Constant.IDENTITY_KEY, all.toString());
			activity.startActivity(intent);
		} else if (id == R.id.text_right) {

			if (!CommonUtility.isNull(GlobalSettings.sUser)) {
				Intent intent = null;
				if (CommonUtility.isDoctor()) {
					ArrayList<OActionItem> dataProvider = new ArrayList<OActionSheet.OActionItem>();
					OActionItem item = null;
					item = new OActionItem();
					try {
						
						Log.i("testdoctorchat", "question:" + question);
						
						
						isComment = question.getInt("Status");
						
						/**
						 * 
						 * 问题的解答状态
						 * 
						 */
						
						
						
						/**
						 * 会话状态
						 * IS_RSAcceptMSG 是已关闭的判断  ---> 
						 * 
						 * 1为会话中 0为关闭会话
						 * 
						 * 
						 */
						
						
						/**
						 * Is_Appraise
						 * 
						 * 0未评价 1已评价
						 * 
						 */												
						if (isComment == 3 && mUserWrapper != null && mUserWrapper.RelationShip != null) {
							if(mUserWrapper.RelationShip.IS_RSAcceptMSG==1){
								item.setText("关闭会话");
							}else{
								item.setText("启动随访");
							}
						} else {
							item.setText("创建解答");
							
							Log.i("testdoctorchat","创建解答:");

						}
						
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					dataProvider.add(item);
					final OActionSheet<OActionItem> actionSheet = new OActionSheet<OActionSheet.OActionItem>(
							this);
					actionSheet.setCancel("取消");
					actionSheet.setDataProvider(dataProvider);
					actionSheet.show(false, true);
					actionSheet
							.setOnActionItemClickListener(new OnActionItemClickListener<OActionSheet.OActionItem>() {
								@Override
								public void onItemClick(
										OActionSheet<OActionItem> sheet,
										View v, int position,
										OActionItem dataItem) {
									if (position == 1) {
										actionSheet.dismiss();
									}
									if (position == 0) {
										if (isComment == 3) {
											// 关闭会话
											RelationshipSetTask task = new RelationshipSetTask();
											RelationshipSetRequest req = new RelationshipSetRequest();
											req.appname = Constant.APP_NAME;
											if(mUserWrapper.RelationShip.IS_RSAcceptMSG==1){
												
												Log.i("testdoctorchat", "IS_RSAcceptMSG = 0");	
												
												req.IS_RSAcceptMSG = 0;
											}else{
												req.IS_RSAcceptMSG = 1;
										
												Log.i("testdoctorchat", "IS_RSAcceptMSG = 1");
											
											}
										
											try {
												req.rsuid = patient.getLong("Uid");
												req.token = GlobalSettings.sToken;
												task.setRequest(req);
												add(task);
												task.addListener(new NetTaskListener<RelationshipSetTask.RelationshipSetRequest, RelationshipSetTask.RelationshipSetResponse>() {

													@Override
													public void onComplete(
															INetTask<RelationshipSetRequest, RelationshipSetResponse> task,
															RelationshipSetResponse response) {
														if(response!=null&&response.ResultCode==200){
															mUserWrapper .RelationShip= response.Res;
															if(mUserWrapper.RelationShip.IS_RSAcceptMSG==1){
																mSuiFang.setVisibility(View.GONE);
																
																btn_voice.setVisibility(View.VISIBLE);
																
															}else{
																mSuiFang.setVisibility(View.VISIBLE);
																
																btn_voice.setFocusable(false);
																btn_voice.setEnabled(false);
																btn_keyboard.setFocusable(false);
																btn_keyboard.setEnabled(false);
																btn_more.setFocusable(false);
																btn_more.setEnabled(false);
																
															}													
															btn_press_to_voice.setVisibility(View.GONE);
														}
													}

													@Override
													public void onException(
															INetTask<RelationshipSetRequest, RelationshipSetResponse> task,
															Exception e) {
														
													}
												});
												
											} catch (JSONException e) {
												e.printStackTrace();
											}
											
										} else {
											Intent intent = new Intent(
													activity,
													ZhiliaofanganActivity.class);
											intent.putExtra(
													Constant.IDENTITY_KEY,
													all.toString());
											activity.startActivity(intent);
										}
									}
								}
							});

				} else {
					intent = new Intent(activity,
							CreateProjectCommentActivity.class);
					QuestionAnswer data = null;
					try {
						data = JsonUtil.convertFromObject(all,
								QuestionAnswer.class);
					} catch (Exception e) {
						e.printStackTrace();
					}
					QuestionAnswerExtra extra = new QuestionAnswerExtra();

					extra.setQuestionAnswer(data);

					if (extra.putTo(intent)) {
						activity.startActivity(intent);
					}
				}
			} else {
				activity.startActivity(new Intent(activity, LoginActivity.class));
			}
		}
	}

	void send(ChatVo chatVo) {
		JSONObject object = new JSONObject();
		try {
			object.put("Qid", qid);
			object.put("Uid", GlobalSettings.sUser.Uid);
			object.put("readState", true);
			// object.put("Uid", GlobalSettings.sUser.Uid);
			// object.put("Uid", doctor.getString("Uid"));

			if (chatVo.contentType == Constant.TYPE_CHAT_VOICE) {
				object.put("FilePath", chatVo.content);
				object.put("FileLength", chatVo.voiceLength);
			} else {
				object.put("Content", chatVo.content);
				object.put("FilePath", "");
			}
			object.put("type", chatVo.contentType);
			JsonDate date = new JsonDate();
			date.setTime(System.currentTimeMillis());
			object.put("CreateTime", // CommonUtility.getCurrentDate(0, 19)
					date);
			if (chatVo.isLocal) {
				object.put("local", true);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (chatVo.contentType == Constant.TYPE_CHAT_TEXT) {
			params_record.put("Content", chatVo.content);
			params_record.remove("Pic");
			params_record.remove("psv");
			submitData();
		} else if (chatVo.contentType == Constant.TYPE_CHAT_PIC) {
			params_record.put("Pic", chatVo.content);
			params_record.remove("Content");
			params_record.remove("psv");
			uploadPic(chatVo.content);
		} else if (chatVo.contentType == Constant.TYPE_CHAT_VOICE) {

			params_record.remove("Content");
			params_record.remove("Pic");
			params_record.put("FileLength", chatVo.voiceLength);
			params_record.put("psv", new File(chatVo.content));
			submitData();
		}

		/**
		 * Uid 为本人的
		 */

		try {
			object.put("Uid", GlobalSettings.sUid);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		put2Cache(object);
		adapter.notifyUpdate();
		list_session.getListView().smoothScrollToPosition(
				list_session.getListView().getBottom());
	}

	void submitData() {
		RequestTaskIntercept.requestIntercept(activity, Constant.URL.REQUEST,
				new RequestHandler(activity, new HandlerCallback() {

					@Override
					public void callback(Object o) {
						if (!CommonUtility.isNull(o)) {
							JSONObject object = (JSONObject) o;

							if (!CommonUtility.response200(object)) {
								// CommonUtility.toast(activity, "内容发送失败");
							} else {
								Intent intent = new Intent(
										Constant.RECIVER_CHAT_LIST);
								// intent.putExtra(Constant.IDENTITY_KEY,
								// recordArray.get(0).toString());
								sendBroadcast(intent);
							}
						}
					}
				}), false, params_record);
	}

	void uploadPic(String path) {
		if (!CommonUtility.isNull(path)) {
			HashMap<String, Object> params = new HashMap<String, Object>();
			params.put(Constant.PARAM_TOKEN, GlobalSettings.sToken);
			params.put("pic", new File(path));
			params.put(Constant.PARAM_API, "SYS.UploadPic");
			RequestTaskIntercept.requestIntercept(activity,
					Constant.URL.REQUEST,
					new RequestHandler(activity, callback), false, params);
		}
	}

	HandlerCallback callback = new HandlerCallback() {

		@Override
		public void callback(Object o) {
			if (!CommonUtility.isNull(o)) {
				JSONObject object = (JSONObject) o;
				try {
					if (CommonUtility.response200(object)) {
						String path = object.getString(Constant.JSON_PARAM_RES);
						params_record.put("Pic", path);
						submitData();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	};

	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
	//	loadData();
	}

	@Override
	public void onPullUpToLoadMore(PullToRefreshBase<ListView> refreshView) {

	}

	protected void onClickMore() {
		ArrayList<OActionItem> dataProvider = new ArrayList<OActionSheet.OActionItem>();
		OActionItem item = null;
		item = new OActionItem();
		item.setText("拍照");
		dataProvider.add(item);
		item = new OActionItem();
		item.setText("从手机相册选择");
		dataProvider.add(item);
		OActionSheet<OActionItem> actionSheet = new OActionSheet<OActionSheet.OActionItem>(
				this);
		actionSheet.setCancel("取消");
		actionSheet.setDataProvider(dataProvider);
		actionSheet.show(false, true);
		actionSheet
				.setOnActionItemClickListener(new OnActionItemClickListener<OActionSheet.OActionItem>() {

					@Override
					public void onItemClick(OActionSheet<OActionItem> sheet,
							View v, int position, OActionItem dataItem) {
						if (position == 0) {
							TakePhotoTask task = new TakePhotoTask(
									ChatActivity.this,
									GlobalSettings.REQUEST_CODE_TAKE_PHOTO);
							task.takePhoto();
							task.setListener(new TakePhotoListener() {

								@Override
								public void onComplete(Uri uri) {
									onPicPhotoComplete(uri.getPath());
								}
							});
						}
						if (position == 1) {
							PickPhotoTask task = new PickPhotoTask(
									ChatActivity.this,
									GlobalSettings.REQUEST_CODE_PICK_PHOTO);
							task.pickPhoto();
							task.setListener(new PickPhotoListener() {

								@Override
								public void onComplete(Uri uri) {
									onPicPhotoComplete(uri.getPath());
								}
							});
						}
					}
				});
	}

	protected void onPicPhotoComplete(String path) {
		ChatVo vo = new ChatVo();
		vo.content = path;
		vo.contentType = Constant.TYPE_CHAT_PIC;
		vo.isLocal = true;
		send(vo);
	}

	protected void onDestroy() {
		super.onDestroy();
		/*
		 * String unSendMsg = CommonUtility.getText(edit_sendmessage);
		 * dbUtil.saveOrUpdate(getClass().getSimpleName(), unSendMsg, uid +
		 * "_drafts");
		 */

		updateReadSate();
		CommonUtility.unRegisteReciver(activity, receiver);
	}

	private void updateReadSate() {
		new Thread(new Runnable() {

			@Override
			public void run() {

				ArrayList<Object> data = new ArrayList<Object>();
				try {
					for (int i = 0; i < recordArray.size(); i++) {
						JSONObject object = new JSONObject(
								(recordArray.get(i).toString()));
						
						Log.i("testchatdata", "onDestroy.object:" + object);
						if (object.has("readState")) {
							if (!object.getBoolean("readState")) {
								object.put("readState", true);
							}
						}
						
						
						data.add(object);

					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				
				Log.i("testchatdata", "data.size:" + data.size());
				
				
				put2Cache(data, uid);
				notifiSessionViewNoRead();
			}
		}).start();
	}

	protected void onStop() {
		super.onStop();
		adapter.stopVoice();
	}

	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {

			try {
				boolean isFinish = intent.getBooleanExtra(
						Constant.IDENTITY_KEY_1, false);
				if (isFinish) {
					finishTip();
				} else {
					JSONArray array = new JSONArray(
							intent.getStringExtra(Constant.IDENTITY_KEY));
					/*
					 * JSONObject question = KeyValueUtil.get(array,
					 * "question.qid");
					 */

					// JSONObject question = KeyValueUtil.get(array,
					// "sender.uid");

					// JSONObject question = KeyValueUtil.get(array, "content");

					JSONObject receiver = KeyValueUtil.get(array,
							"receiver.uid");
					// int answerQid = question.getInt("Value");

					JSONObject question = KeyValueUtil.get(array, "content");
					/**
					 * object = new JSONObject(KeyValueUtil.get(array,
					 * "content").getString("Value"));
					 */

					int answerQid = new JSONObject(KeyValueUtil.get(array,
							"content").getString("Value")).getInt("Qid");

					if (//answerQid == qid&& 
							GlobalSettings.sUser.Uid == receiver
									.getInt("Value")) {

						JSONObject oo = new JSONObject(KeyValueUtil.get(array,
								"content").getString("Value"));
						setReaded(oo.getString("id"));
						// put2Cache(oo);
						recordArray.add(0, oo);

						adapter.notifyUpdate();
						list_session.getListView().smoothScrollToPosition(
								list_session.getListView().getBottom());
						// list_session.getListView().setSelection(
						// list_session.getListView().getCount() - 1);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};

	
	  @Override 
	  protected void onPause() { 
		  super.onPause(); 
		  currentQid = 0;
	//  MobclickAgent.onPause(this);
	  }
	 
	  @Override 
	  protected void onResume() {
		  super.onResume();
		  currentQid = qid;
	  initQuestion();
	  //MobclickAgent.onResume(this); 
	  }
	 

	@Override
	protected void onStart() {
		super.onStart();
		
		try {
			if (question != null && !question.toString().equals("")) {
				text_question_name.setTextAddQuotes(
						question.getString("Content"), ChatActivity.this);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	/**
	 * method desc： 设置当前未读消息为已读
	 * 
	 * @param ids
	 */
	void setReaded(String ids) {
		readParams.put("ids", ids);
		RequestTaskIntercept.requestIntercept(activity, Constant.URL.REQUEST,
				new RequestHandler(activity, new HandlerCallback() {

					@Override
					public void callback(Object o) {
						Intent intent = new Intent(Constant.RECIVER_CHAT_LIST);
						sendBroadcast(intent);
					}
				}), false, readParams);
	}

	void put2Cache(JSONObject object) {
		if (!CommonUtility.isNull(recordArray)) {
			recordArray.add(0, object);
			dbUtil.saveOrUpdate(getClass().getSimpleName(), recordArray, uid);
		}
	}

	// 患处图片点击事件
	OnClickListener listener = new OnClickListener() {

		@Override
		public void onClick(View view) {
			int position = (Integer) view.getTag();
			String[] pics = (String[]) view.getTag(R.id.tag_obj);
			PhotoExtra extra = new PhotoExtra();
			extra.setDisplayedIndex(position);
			extra.setPhotos(OUtil.asArrayList(pics));
			Intent intent = new Intent(activity, PhotoActivity.class);
			extra.putTo(intent);
			activity.startActivity(intent);
		}
	};

	void finishTip() {
		try {
			// rl_input.setVisibility(View.GONE);
			View chatFinishView = LayoutInflater.from(activity).inflate(
					R.layout.include_chat_finish, null);
			TextView textFinishView = (TextView) chatFinishView
					.findViewById(R.id.text_chat_finish);
			list_session.getListView().addFooterView(chatFinishView);
			if (CommonUtility.isDoctor()) {
				textFinishView.setText("问题解答完毕");
			} else {
				// 是否已经评价，未评价的显示创建评价并点击跳转
				int isAppraise = question.getInt("Is_Appraise");
				if (isAppraise == 1) {
					textFinishView.setText("解答完毕");
				} else {
					textFinishView
							.setText(Html
									.fromHtml("<font color='#ffffff'>解答完毕，</font><font color='#ff7f00'>创建评价</font>"));
					chatFinishView.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							Intent intent = new Intent(activity,
									CreateProjectCommentActivity.class);

							// intent.putExtra(Constant.IDENTITY_KEY,
							// view.getTag().toString());

							intent.putExtra(Constant.IDENTITY_KEY,
									question.toString());

							// intent.putExtra(Constant.IDENTITY_KEY, value);

							/*
							 * intent.putExtra(Constant.IDENTITY_KEY,
							 * all.toString());
							 */
							activity.startActivity(intent);
						}
					});
					setNavRightBtn("创建评价");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@SuppressLint("NewApi")
	public static class ChatAdapter extends BaseListAdapter implements
			OnClickListener, OnLongClickListener {

		protected BitmapUtils mBitmapUtils;

		public static interface IMsgViewType {
			int IMVT_COM_MSG = 0;
			int IMVT_TO_MSG = 1;
		}

		public int getItemViewType(int position) {
			JSONObject object = (JSONObject) getItem(list.size() - position - 1);
			try {
				int type = 0;
				boolean isMine = object.getInt("Uid") == GlobalSettings.sUser.Uid;
				if (!isMine) {
					type = IMsgViewType.IMVT_COM_MSG;
				} else {
					type = IMsgViewType.IMVT_TO_MSG;
				}
				return type;
			} catch (Exception e) {
				e.printStackTrace();
			}
			return 0;
		}

		public int getViewTypeCount() {
			return 2;
		}

		private JSONObject all, doctor, patient;

		public ChatAdapter(Activity activity, ArrayList<Object> array,
				JSONObject all) {
			super(activity, array);
			mBitmapUtils = new BitmapUtils(activity);
			this.all = all;
			try {
				this.doctor = all.getJSONObject("Doctor_User");
				this.patient = all.getJSONObject("Patient_User");
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

		class ViewHolder {
			TextView text_date, text_content, chat_voice_time;
			OImageView head_icon;
			ImageView img;
			ImageView chat_type_img_voice;
			RelativeLayout bg_layout;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			position = list.size() - position - 1;

			JSONObject object = (JSONObject) getItem(position);

			try {
				boolean isMine = (object.getInt("Uid") == GlobalSettings.sUser.Uid);
				ViewHolder viewHolder = null;
				if (CommonUtility.isNull(convertView)) {
					viewHolder = new ViewHolder();

					if (isMine) {
						convertView = inflater.inflate(
								R.layout.item_chatting_msg_text_right, null);
					} else {
						convertView = inflater.inflate(
								R.layout.item_chatting_msg_text_left, null);
					}
					viewHolder.text_date = (TextView) convertView
							.findViewById(R.id.tv_sendtime);
					viewHolder.head_icon = (OImageView) convertView
							.findViewById(R.id.iv_userhead);
					viewHolder.text_content = (TextView) convertView
							.findViewById(R.id.chat_text);
					viewHolder.img = (ImageView) convertView
							.findViewById(R.id.imgLayout_show);
					viewHolder.img
							.setOnClickListener(new View.OnClickListener() {

								@Override
								public void onClick(View v) {
									String url = v.getTag().toString();
									PhotoExtra extra = new PhotoExtra();
									ArrayList<String> urls = new ArrayList<String>();
									urls.add(url);
									extra.setPhotos(urls);
									Context context = v.getContext();
									Intent intent = new Intent(context,
											PhotoActivity.class);
									extra.putTo(intent);
									context.startActivity(intent);
								}
							});
					viewHolder.chat_type_img_voice = (ImageView) convertView
							.findViewById(R.id.chat_type_img_voice);
					viewHolder.bg_layout = (RelativeLayout) convertView
							.findViewById(R.id.layout_chat_parent);
					viewHolder.chat_voice_time = (TextView) convertView
							.findViewById(R.id.chat_voice_time);
					viewHolder.bg_layout.setOnClickListener(this);
					viewHolder.bg_layout.setOnLongClickListener(this);
					CommonUtility.setViewHolderTag(convertView, viewHolder);
				} else {
					viewHolder = (ViewHolder) CommonUtility
							.getViewHolderTag(convertView);
				}

				String preTime = null;
				Session session = JsonUtil.convert(object.toString(),
						Session.class);
				if (position < getCount() - 1) {
					Session presession = JsonUtil.convert(
							((JSONObject) getItem(position + 1)).toString(),
							Session.class);

					/*
					 * preTime = CommonUtility.getTimeDiff(
					 * CommonUtility.formatDateSession(
					 * presession.CreateTime.toString(), 0, 19), 0, 19);
					 */

					preTime = CommonUtility.getTimeDiff(CommonUtility
							.formatDateSession(
									presession.CreateTime.toString(), 0, 16),
							0, 16);
				}

				/*
				 * String currentTime = CommonUtility.getTimeDiff(CommonUtility
				 * .formatDateSession(session.CreateTime.toString(), 0, 19),
				 * 0,19);
				 */

				String currentTime = CommonUtility.getTimeDiff(
						CommonUtility.formatDateSession(
								session.CreateTime.toString(), 0, 16), 0, 16);

				if (currentTime.equals(preTime)) {
					viewHolder.text_date.setVisibility(View.GONE);
				} else {
					viewHolder.text_date.setVisibility(View.VISIBLE);
					viewHolder.text_date.setText(currentTime);
				}

				String iconPath = null;
				if (CommonUtility.isDoctor()) {
					if (isMine) {
						iconPath = GlobalSettings.sUser.Pic + Constant.IMG_TH;
					} else {
						iconPath = patient.getString("Pic") + Constant.IMG_TH;
					}
				} else {
					if (isMine) {
						iconPath = GlobalSettings.sUser.Pic + Constant.IMG_TH;
					} else {
						iconPath = doctor.getString("Pic") + Constant.IMG_TH;
					}
				}

				RelativeLayout.LayoutParams linearParams = (RelativeLayout.LayoutParams) viewHolder.bg_layout
						.getLayoutParams();
				linearParams.width = LayoutParams.WRAP_CONTENT;
				linearParams.height = LayoutParams.WRAP_CONTENT;

				final String path = iconPath;

				mBitmapUtils.display(viewHolder.head_icon,
						GlobalSettings.SERVER_IMG_URL + path,
						new OBitmapLoadCallBack<View>());
				CommonUtility.displayHeadImage(viewHolder.head_icon,
						mBitmapUtils, GlobalSettings.SERVER_IMG_URL + path,
						convertView.getResources(), GlobalSettings.sUser.Sex);
				String voice_path = object.getString("FilePath");

				if (!CommonUtility.isNull(voice_path)) {
					viewHolder.chat_type_img_voice.setVisibility(View.VISIBLE);
					viewHolder.text_content.setVisibility(View.GONE);
					viewHolder.img.setVisibility(View.GONE);
					final AnimationDrawable drawable = (AnimationDrawable) viewHolder.chat_type_img_voice
							.getBackground();
					if (!CommonUtility.isNull(preMPAddress)) {
						String curr = RemoteImageDownloader.getFileNameString(
								voice_path, false);
						String playing = RemoteImageDownloader
								.getFileNameString(preMPAddress, false);
						if (curr.equals(playing)) {
							viewHolder.chat_type_img_voice.post(new Runnable() {
								@Override
								public void run() {
									drawable.start();
								}
							});
						} else {
							viewHolder.chat_type_img_voice.post(new Runnable() {
								@Override
								public void run() {
									drawable.stop();
									drawable.selectDrawable(0);
								}
							});
						}
					} else {
						viewHolder.chat_type_img_voice.post(new Runnable() {
							@Override
							public void run() {
								drawable.stop();
								drawable.selectDrawable(0);
							}
						});
					}

					if (!object.has("is_local")) {
						// 将本地文件路径保存
						CommonUtility.setImageIdentityTag(viewHolder.bg_layout,
								voice_path);
						RemoteVoiceDownloader.downloadVoice(voice_path,
								new ImageHandler(activity, callBack,
										viewHolder.bg_layout));
					}

					viewHolder.bg_layout.setTag(R.id.tag_obj,
							viewHolder.chat_type_img_voice);

					// 设置录音的长度
					DisplayMetrics dm = new DisplayMetrics();
					activity.getWindowManager().getDefaultDisplay()
							.getMetrics(dm);
					String voice_time = object.getString("FileLength");

					if (!CommonUtility.isNull(voice_time)) {
						int voiceTime = Integer.parseInt(voice_time);
						if (voiceTime > 0) {
							if (voiceTime < 3)
								voiceTime = 3;
							int width = CommonUtility.dip2px(activity, 45)
									+ voiceTime
									* CommonUtility.dip2px(activity, 10);
							linearParams.width = width;
							viewHolder.bg_layout.setLayoutParams(linearParams);
						}
						viewHolder.chat_voice_time.setText(CommonUtility
								.isNull(voice_time) ? "" : (voice_time + "\""));
					}
					viewHolder.chat_voice_time.setVisibility(View.VISIBLE);
				} else {
					viewHolder.chat_type_img_voice.setVisibility(View.GONE);
					if (!CommonUtility.isNull(object.getString("Content"))) {
						viewHolder.text_content.setText(object
								.getString("Content"));
						viewHolder.text_content.setVisibility(View.VISIBLE);
						viewHolder.img.setVisibility(View.GONE);
					} else if (object.getJSONArray("Pic").length() > 0) {
						viewHolder.text_content.setVisibility(View.GONE);
						viewHolder.img.setVisibility(View.VISIBLE);
						final String chatImagePath = object.getJSONArray("Pic")
								.getString(0) + Constant.IMG_TH;
						CommonUtility.setImageIdentityTag(viewHolder.img,
								chatImagePath);
						mBitmapUtils.display(viewHolder.img,
								GlobalSettings.SERVER_IMG_URL + chatImagePath);
						viewHolder.img.setTag(GlobalSettings.SERVER_IMG_URL
								+ object.getJSONArray("Pic").getString(0)
								+ Constant.IMG_SRC);
					}
					if (object.has("local")) {
						boolean local = object.getBoolean("local");
						if (local) {
							viewHolder.img.setVisibility(View.VISIBLE);
							viewHolder.text_content.setVisibility(View.GONE);
							mBitmapUtils.display(viewHolder.img,
									object.getString("Content"));
							viewHolder.img.setTag(object.getString("Content"));
						}
					}
					viewHolder.chat_voice_time.setVisibility(View.GONE);
				}
				viewHolder.bg_layout.setTag(object);
				convertView.setTag(object);
			} catch (Exception e) {
				e.printStackTrace();
			}

			return convertView;
		}

		ImageHandlerCallback callBack = new ImageHandlerCallback() {

			@Override
			public void callback(Object o, View view) {
				Object obj = view.getTag(R.id.tag_obj_image_identity);
				if (!CommonUtility.isNull(obj)) {
					String identity = obj.toString();
					if (o.toString().contains(
							RemoteImageDownloader.getFileNameString(identity,
									false))) {
						JSONObject object = new JSONObject();
						try {
							object.put("FilePath", o.toString());
						} catch (Exception e) {
						}
						view.setTag(object);
						view.setOnClickListener(ChatAdapter.this);
					}
				}
			}
		};

		JSONObject preEntity = null;
		AnimationDrawable preAd = null;
		MediaPlayer mp = null;
		private String preMPAddress = null;

		@Override
		public void onClick(View view) {
			JSONObject object = (JSONObject) view.getTag();

			if (!CommonUtility.isNull(object)) {
				try {
					// 0是普通会话 1是下诊断时候系统发出来的 3是用户评价时候系统发出来的

					if (object.has("Session_Type")
							&& object.getInt("Session_Type") == 1) {
						Intent intent = new Intent(activity,
								QuestionDetailActivity.class);
						intent.putExtra(Constant.IDENTITY_KEY, all.toString());
						activity.startActivity(intent);
					} else {
						String filePath = object.getString("FilePath");

						if (!CommonUtility.isNull(filePath)) {
							ImageView imageview = (ImageView) view
									.getTag(R.id.tag_obj);
							AnimationDrawable ad = (AnimationDrawable) imageview
									.getBackground();
							if (preEntity == object) {
								if (mp != null && mp.isPlaying()) {
									mp.stop();
									mp.release();
									if (preAd != null) {
										preAd.stop();
										preAd.selectDrawable(0);
										preAd = null;
									}
									mp = null;
									return;
								}
							} else {
								if (preEntity != null && mp != null) {
									mp.stop();
									mp.release();
									mp = null;
									if (preAd != null) {
										preAd.stop();
										preAd.selectDrawable(0);
										preAd = null;
									}
								}
							}

							preMPAddress = filePath;
							mp = new MediaPlayer();
							mp.setDataSource(preMPAddress);
							mp.prepare();
							mp.start();
							ad.start();
							preEntity = object;
							preAd = ad;

							mp.setOnCompletionListener(new CustomCompletionListener(
									ad));
						}
					}
				} catch (IllegalArgumentException e) {

					e.printStackTrace();
				} catch (SecurityException e) {
					e.printStackTrace();
				} catch (IllegalStateException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

		public void stopVoice() {
			try {
				if (mp != null && mp.isPlaying()) {
					mp.stop();
					mp.release();
					if (preAd != null) {
						preAd.stop();
						preAd.selectDrawable(0);
						preAd = null;
					}
					preMPAddress = null;
					mp = null;
				}
			} catch (Exception e) {
			}
		}

		class CustomCompletionListener implements OnCompletionListener {

			private AnimationDrawable ad;

			CustomCompletionListener(AnimationDrawable ad) {
				this.ad = ad;
			}

			@Override
			public void onCompletion(MediaPlayer mp) {
				if (ad != null) {
					ad.stop();
					ad.selectDrawable(0);
					ad = null;
				}
				mp.release();
				preEntity = null;
				preMPAddress = null;
				mp = null;
			}
		}

		@Override
		public boolean onLongClick(View view) {
			try {
				JSONObject object = (JSONObject) view.getTag();
				String voice_path = object.getString("FilePath");
				if (CommonUtility.isNull(voice_path)) {
					DeviceUtility.SystemOperate.copy2Clipboard(activity,
							object.getString("Content"));
				} else {
					CommonUtility.tip(activity, "暂不支持此类型的内容复制");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return true;
		}

	}

	public static void put2Cache(ArrayList<Object> data, int uid) {
		if (!CommonUtility.isNull(data)) {
			if (data.size() > 0) {
				dbUtil.saveOrUpdate("ChatActivity", data, uid);
			}
		}
	}
}